<template>
  <div class="exercise-container">
    <div class="examLeftContainer">
      <!-- 测试头部的说明内容 -->
      <div class="exam-instructions">
        <div class="exam-title">{{ exam.name }}</div>
        <div class="part2 explain">
          <span>题量: {{ exam.totalNum }}</span
          >&nbsp;&nbsp;&nbsp;
          <span>满分: {{ exam.totalScore }}</span>
        </div>
        <div class="part3 explain">
          作答时间: {{ exam.start_date }} 至 {{ exam.end_date }}
        </div>
        <span v-show="exam.score" class="explain">得分：{{ exam.score }}</span>
      </div>
      <!-- 所有的题目 -->
      <exam-paper
        :topics="topics"
        :finish="finish"
        :type="type"
        :answer="answer"
        :reviewResult="reviewResult"
        :criterion="criterion"
      ></exam-paper>
    </div>
    <!-- 答题卡 -->
    <topic-sheet
      :isCanBeSubmit="isCanBeSubmit"
      :answerSheet="answer"
      :topics="topics"
      :watchIndex="watchIndex"
      :floorHeight="floorHeight"
      :scrollByIndex="scrollByIndex"
      :changeWatchingIndex="changeWatchingIndex"
    ></topic-sheet>
  </div>
</template>

<script>
import CommonExercise from "@/components/CommonExercise.vue";
import ExamPaper from "@/components/ExamPaper.vue";
import TopicSheet from "@/components/TopicSheet.vue";
import { getExamTopics, getTestTopics } from "@/services/student";
import { mapState } from "vuex";
export default {
  name: "Exercise",
  data() {
    return {
      answerSheet: [],
      answer: [],
      watchIndex: 0,
      floorHeight: [],
      topics: {},
      criterion: {},
      reviewResult: [],
      type: -1,
      exam: {
        name: "Exercise",
        totalNum: 10,
        totalScore: 100,
        start_date: "2023-5-4 10:46:00",
        end_date: "2023-5-4 12:46:00",
        score: 82,
      },
      myType: 0,
    };
  },
  components: {
    TopicSheet,
    CommonExercise,
    ExamPaper,
  },
  methods: {
    submit() {
      console.log("submiting...");
    },
    // 通过传递索引
    finish(eIndex, data) {
      // // 获取项
      // this.answerSheet[eIndex] = data;
      // this.topics[eIndex].done = true;
      // this.$set(this.answerSheet, eIndex, data);
      this.$set(this.answer, eIndex, data);
    },
    scrollByIndex(index) {
      console.log("index: ", index);
      const container = document.querySelector(".el-main");
      container.scrollTop = this.floorHeight[index];
    },
    changeWatchingIndex(index) {
      this.watchIndex = index;
    },
    getStorageAnswerByExamID(exam_id) {
      const exerciseAnswerArr =
        JSON.parse(localStorage.getItem("exerciseAnswerArr")) || [];
      let answerSheet = [];
      exerciseAnswerArr.forEach((e) => {
        if (e.exam_id == exam_id) {
          answerSheet = e.answerSheet;
        }
      });
      return answerSheet;
    },
    // 依据section_id换取存的数据
    getStorageAnswerBySectionID(section_id) {
      const { student_id } = JSON.parse(localStorage.getItem("userInfo"));
      const exerciseAnswerArr =
        JSON.parse(localStorage.getItem("exerciseAnswerArr")) || [];
      let answerSheet = [];
      let exam_id = this.course_id + "_" + section_id;
      exerciseAnswerArr.forEach((e) => {
        if (e.exam_id == exam_id) {
          answerSheet = e.answerSheet;
        }
      });
      return answerSheet;
    },
    // 获取试题的逻辑
    initTopics() {
      // 根据不同的类型来获取不同的
      const { exam_id } = this.$route.query;
      const { student_id } = JSON.parse(localStorage.getItem("userInfo"));
      if (exam_id) {
        // 就是考试
        getExamTopics(exam_id, student_id).then((res) => {
          this.topics = res.data.data.topics;
          this.answer = res.data.data.answer;
          this.criterion = res.data.data.criterion;
          this.reviewResult = res.data.data.reviewResult;
          this.type = res.data.data.type;
          // console.log(this.answer, this.reviewResult, this.type);
        });
      } else {
        this.topics = this.$store.state.studyAbout.topics;
        this.answer = this.$store.state.studyAbout.answer;
        this.criterion = this.$store.state.studyAbout.criterion;
        this.reviewResult = this.$store.state.studyAbout.reviewResult;
        this.type = this.$store.state.studyAbout.type;
      }
    },
  },
  mounted() {
    // console.log('111')
    const { exam_id, section_id } = this.$route.query;
    console.log("exam_id, section_id : ", exam_id, section_id);

    // if (exam_id) {
    //   this.answer = this.getStorageAnswerByExamID(exam_id);
    // } else if (section_id) {
    //   this.answer = this.getStorageAnswerBySectionID(section_id);
    // }
    // if (this.answer.length == 0) {
    //   this.answer = this.answerSheet;
    // }

    // 如果有exam_id，那么说明是考试，用考试的获取方法
    this.initTopics();

    // this.initTopics();
    // console.log("answer", this.answerSheet);
    // console.log("reviewRe", this.reviewResult);
    /**
     * 获取当前距离顶的距离，然后找到对应的index，用这个index去让对应的高亮显示
     */
    // 获取所有需要导航的楼层
    const container = document.querySelector(".el-main");
    const floors = document.querySelectorAll(".topic_item");
    // console.log(floors);
    const floorHeight = [];
    floors.forEach((e, i) => (floorHeight[i] = e.offsetTop));
    // console.log(floorHeight);
    this.floorHeight = floorHeight;

    container.addEventListener("scroll", scrolling);
    const that = this;

    function scrolling() {
      // 获取当前距离顶的高度
      const floorH = parseInt(document.querySelector(".el-main").scrollTop);
      // 发现每个都少了两点，感觉像是
      // console.log('floorH',floorH)
      const index = findIndex(floorHeight, floorH);
      // console.log(index);
      // 用index去让高亮显示
      that.watchIndex = index;
    }

    this.scrolling = scrolling;

    function findIndex(arr, e) {
      // 给一个有序数组，找到对应的索引位置
      // [0,1,2,3] => 2.5 找到第一个比他小的
      for (let i = arr.length - 1; i >= 0; i--) {
        if (arr[i] < e) {
          return i + 1;
        }
      }
      return 0;
    }
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.scrolling);
  },
  computed: {
    // ...mapState("studyAbout", {
    //   course_id: (state) => state.course.course_id,
    //   section_id: (state) => state.currentSection.id,
    //   answerSheet: (state) => state.answer,
    //   criterion: (state) => state.criterion,
    //   reviewResult: (state) => state.reviewResult,
    //   type: (state) => state.type,
    // }),
    isCanBeSubmit() {
      return this.type == 0 || this.type == 1;
    },
  },
};
</script>

<style lang='less' scoped>
.exercise-container {
  width: calc(100% - 40px);
  min-height: calc(100% - 40px);
  background-color: #e9eef3;
  padding: 20px;

  .examLeftContainer {
    width: 800px;
    padding: 20px;
    min-height: 600px;

    background-color: #fff;
    border-radius: 20px;

    .exam-instructions {
      border-bottom: 1px solid #ccc;
      height: 80px;
      padding: 10px;
      display: flex;
      flex-direction: column;
      justify-content: space-around;

      .exam-title {
        line-height: 25px;
        font-size: 18px;
        color: #181e33;
        font-weight: bold;
      }

      .explain {
        line-height: 16px;
        color: #a8a8b3;
        font-size: 14px;
      }
    }
  }
}
</style>